#include "ConectorMySql.h"

#include "Logger.h"
#include <sstream>
#include <iostream>


ConectorMySql::ConectorMySql(DatosConexion* unDatoConexion ){
	this->datosConexion = unDatoConexion ;
}

bool ConectorMySql::conectar(){
	bool res = false;
	mysql_init(&this->mysql);
	this->connection = mysql_real_connect(&this->mysql,this->datosConexion->getHost()->c_str(),this->datosConexion->getUsuario()->c_str(),this->datosConexion->getPassword()->c_str(),this->datosConexion->getDb()->c_str(),0,0,0);
	if (this->connection == NULL) {
		std::stringstream ss;
		ss << "Imposible conectar a la BD - " << mysql_error(&this->mysql) ;
		Logger::getInstance()->err(ss.str());
		res = false;
	}else{
		Logger::getInstance()->debug("Conectado correctamnte a la BD");
		res = true ;
	}
	Logger::getInstance()->flush();
	return res ;
}

bool ConectorMySql::ejecutarConsulta(const string& query){
	bool res = false ;
	if(!this->connection)
		return res ;

	int query_state;
	query_state = mysql_query(this->connection, query.c_str());
	if (query_state !=0) {
		std::stringstream ss;
		ss << mysql_error(this->connection) ;
		Logger::getInstance()->err(ss.str());
		res = false;
	}else{
		this->result = mysql_store_result(this->connection);
		res = true ;
	}
	Logger::getInstance()->flush();
	return res ;
}

char** ConectorMySql::getNextResult(){
	if(this->result){
		if ( ( this->row = mysql_fetch_row(this->result)) != NULL ) {						
			return this->row;
		}
	}else{
		Logger::getInstance()->warn("No hay resultados disponibles.");
	}
	return 0 ;
}

void ConectorMySql::desconectar(){

	if(this->result)
		mysql_free_result(this->result);
	mysql_close(this->connection);

}

bool ConectorMySql::isConectado(){
	return (this->connection != 0) ;
}

bool ConectorMySql::validarConexion(){
	bool con = false;
	con = this->conectar();
	if(con){
		this->result = 0;
		this->desconectar();
	}
	return con ;
}